<?php
/**
 * Redis.php
 * Redis日志驱动
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2018-06-17 23:59:58
 */

namespace App\Utils\Log;
use Illuminate\Support\Facades\Redis;

class RedisDrive {

    public $redis;
    private static $instance;

    function __construct(){
        $this->redis    = Redis::connection();
    }

    static function getInstance(){
        if(!self::$instance){
            self::$instance    = new self();
        }

        return self::$instance;
    }

    /**
     * 追加日志
     * @param   $key 
     * @param   $content
     * @return  null [<description>]
     */
    function append($key, $content){
        is_string($content) && $content = ['content' => $content];
        $key    = config('cache.prefix').':'.$key;
        $content    = array_merge($content, [
            'datetime'  => date('Y-m-d H:i:s')
        ]);

        $this->redis->lpush($key, json_encode($content));
    }

    /**
     * 获取列表日志
     * @param   $key
     * @param   $page
     * @param   $count
     * @return  list [<description>]
     */
    function list($key, $page = 1, $count = 10){
        $key    = config('cache.prefix').':'.$key;
        $page   = $page <= 1 ? 1 : (int)$page;
        $count  = $count <= 1 ? 10 : (int)$count;
        $start  = ($page - 1) * $count;

        $list   = $this->redis->lrange($key, $start, $start + $count);
        foreach($list as &$item){
            $item   = json_decode($item);
        }

        return $list;

    }

}
